package com.item.yxlottery.yxlottery.activity;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2017/1/5 11:15
 * @文件描述    手动定位,选择城市
 *------------------------------
 */

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.blankj.utilcode.utils.ConvertUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.adapter.SelectorCityAdapter;
import com.item.yxlottery.yxlottery.adapter.SelectorProvinceAdapter;
import com.item.yxlottery.yxlottery.base.BaseActivity;
import com.item.yxlottery.yxlottery.common.MyApplication;
import com.item.yxlottery.yxlottery.service.LocationService;
import com.item.yxlottery.yxlottery.views.StringLoadingDialog;
import com.orhanobut.logger.Logger;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SelectorCityActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.et_selectorcity_storename)
    EditText mEtStorename;

    @Bind(R.id.ib_selectorcity_search)
    ImageButton mIbSearch;

    @Bind(R.id.tv_selectorcity_province)
    TextView mTvProvince;

    @Bind(R.id.rv_selectorcity_cities)
    RecyclerView mRvCities;

    @Bind(R.id.rv_selectorcity_districts)
    RecyclerView mRvDistricts;

    @Bind(R.id.ib_selectorcity_location)
    ImageButton mIbLocation;

    @Bind(R.id.rv_selectorcity_provinces)
    RecyclerView mRvProvinces;

    @Bind(R.id.bt_selectorcity_cancel)
    Button mBtCancel;

    @Bind(R.id.all_selectorcity_camcel)
    LinearLayout mAllSelectorcityCamcel;

    private TextView mTvActionBarTitle;
    private ArrayList<JSONObject> mProvinceList = new ArrayList<>();//所有的省
    private ArrayList<JSONObject> mCityList = new ArrayList<>();//所有的市(地区)
    private ArrayList<JSONObject> mSelectorCityList = new ArrayList<>();//选中的省管辖的市(地区)
    private StringLoadingDialog mLoadingDialog;
    private int mClickProvincePosition = -1;//初始选中省index
    private boolean mSelectorProvinceState;//是否已经选择省
    private String mProvinceAreaId = "";//选中的省id
    private View mStvProvinceLabel;//选中的省角标
    private View mTvSelectorProvince;//选中的省
    private int mClickCityPosition = -1;//初始选中市(地区)index
    private boolean mSelectorCityState;//是否已经选择市(地区)
    private String mCityAreaId = "";//选中的市(地区)id
    private View mStvCityLabel;//选中的市(地区)角标
    private View mTvSelectorCity;//选中的市(地区)
    private String mProvinceAreaName;
    private StringLoadingDialog mLocationLoadingDialog;
    private LocationService mLocationService;
    private MyLocationListener mMyLocationListener;

    @Override
    protected void setCustomActionBar(ImageButton ibActionbarLeft, TextView tvActionBarTitle, ImageButton ibActionbarRight, AutoRelativeLayout layoutActionbar) {
        ibActionbarLeft.setImageResource(R.drawable.leftarrow);
        ibActionbarLeft.setOnClickListener(this);
        tvActionBarTitle.setText("选择省份");
        mTvActionBarTitle = tvActionBarTitle;
        ibActionbarRight.setVisibility(View.GONE);
    }

    @Override
    protected View initView() {
        View view = View.inflate(this, R.layout.activity_selectorcity, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("province")) {
            String province = intent.getStringExtra("province");
            String city = intent.getStringExtra("city");
            if (province.isEmpty()) {
                mTvProvince.setText("定位失败");
            } else {
                mTvProvince.setText(province + city);
            }
        }
        final Handler handler = new Handler();
        mLoadingDialog = new StringLoadingDialog(this);
        mLoadingDialog.setCanceledOnTouchOutside(false);
        mLoadingDialog.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    String s = ConvertUtils.inputStream2String(getAssets().open("shop_area.json"), "utf-8");
                    JSONArray records = JSON.parseArray(((JSONObject) JSON.parse(s)).getString("RECORDS"));
                    for (Object obj : records) {
                        JSONObject jsonObject = (JSONObject) obj;
                        if (jsonObject.getString("area_deep").equals("1")) {
                            mProvinceList.add(jsonObject);
                        } else if (jsonObject.getString("area_deep").equals("2")) {
                            mCityList.add(jsonObject);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mLoadingDialog.dismiss();
                        SelectorProvinceAdapter provinceAdapter = new SelectorProvinceAdapter(SelectorCityActivity.this, R.layout.item_selectorcity_citylist, mProvinceList);
                        mRvProvinces.setLayoutManager(new GridLayoutManager(SelectorCityActivity.this, 4));
                        mRvProvinces.setAdapter(provinceAdapter);
                    }
                });
            }
        }.start();
    }

    @Override
    protected void initEvent() {
        mRvProvinces.addOnItemTouchListener(new OnItemClickListener() {//选择省
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mClickProvincePosition == -1) {//第一次点击
                    mStvProvinceLabel = view.findViewById(R.id.stv_item_selectorcity_lable);
                    mTvSelectorProvince = view.findViewById(R.id.tv_item_selectorcity_city);
                    mStvProvinceLabel.setVisibility(View.VISIBLE);
                    mTvSelectorProvince.setSelected(true);
                } else {
                    // 取消上一次选中的控件的状态
                    mStvProvinceLabel.setVisibility(View.GONE);
                    mTvSelectorProvince.setSelected(false);
                    //获取新选中的控件,改变其状态
                    mStvProvinceLabel = view.findViewById(R.id.stv_item_selectorcity_lable);
                    mTvSelectorProvince = view.findViewById(R.id.tv_item_selectorcity_city);
                    mStvProvinceLabel.setVisibility(View.VISIBLE);
                    mTvSelectorProvince.setSelected(true);
                }
                mSelectorProvinceState = true;
                mClickProvincePosition = position;
                JSONObject object = mProvinceList.get(position);
                mProvinceAreaName = object.getString("area_name");
                mProvinceAreaId = object.getString("area_id");
                if (mProvinceAreaName.contains("北京") || mProvinceAreaName.contains("天津") || mProvinceAreaName.contains("上海") || mProvinceAreaName.contains("重庆")) {
                    mProvinceAreaName = mProvinceAreaName + "市";
                }
                mTvProvince.setText(mProvinceAreaName);
            }
        });
        mRvCities.addOnItemTouchListener(new OnItemClickListener() {//选择市(地区)
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mClickCityPosition == -1) {
                    mStvCityLabel = view.findViewById(R.id.stv_item_selectorcity_lable);
                    mTvSelectorCity = view.findViewById(R.id.tv_item_selectorcity_city);
                    mStvCityLabel.setVisibility(View.VISIBLE);
                    mTvSelectorCity.setSelected(true);
                } else {
                    mStvCityLabel.setVisibility(View.GONE);
                    mTvSelectorCity.setSelected(false);
                    mStvCityLabel = view.findViewById(R.id.stv_item_selectorcity_lable);
                    mTvSelectorCity = view.findViewById(R.id.tv_item_selectorcity_city);
                    mStvCityLabel.setVisibility(View.VISIBLE);
                    mTvSelectorCity.setSelected(true);
                }
                mSelectorCityState = true;
                mClickCityPosition = position;
                JSONObject object = mSelectorCityList.get(position);
                String area_name = object.getString("area_name");
                mCityAreaId = object.getString("area_id");
                if (!mProvinceAreaName.equals(area_name)) {//北京,天津,上海,重庆等
                    mTvProvince.setText(mProvinceAreaName + area_name);
                }
            }
        });
        mBtCancel.setOnClickListener(this);
        mTvProvince.setOnClickListener(this);
        mIbLocation.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_actionbar_left:
                setResultToFragment();
                break;
            case R.id.bt_selectorcity_cancel://确定
                if (mRvProvinces.getVisibility() == View.VISIBLE && mSelectorProvinceState) {//选择省的确定
                    mTvActionBarTitle.setText("选择城市");
                    mRvProvinces.setVisibility(View.GONE);
                    mSelectorCityList.clear();
                    for (JSONObject object : mCityList) {
                        if (object.getString("area_parent_id").equals(mProvinceAreaId)) {
                            mSelectorCityList.add(object);
                        }
                    }
                    SelectorCityAdapter cityAdapter = new SelectorCityAdapter(R.layout.item_selectorcity_citylist, mSelectorCityList);
                    mRvCities.setLayoutManager(new GridLayoutManager(SelectorCityActivity.this, 4));
                    mRvCities.setAdapter(cityAdapter);
                    mRvCities.setVisibility(View.VISIBLE);
                }
                if (mRvCities.getVisibility() == View.VISIBLE && mSelectorCityState) {//选择市(地区)的确定
                    setResultToFragment();
                }
                break;
            case R.id.tv_selectorcity_province://重新选择省
                showProvinces();
                break;
            case R.id.ib_selectorcity_location://重新定位
                showProvinces();
                //显示定位对话框
                mLocationLoadingDialog = new StringLoadingDialog(this);
                mLocationLoadingDialog.setLoadText("定位中...");
                mLocationLoadingDialog.setCanceledOnTouchOutside(false);
                mLocationLoadingDialog.show();
                mLocationService = MyApplication.getLocationService();//获得监听服务
                mMyLocationListener = new MyLocationListener();//监听
                mLocationService.registerListener(mMyLocationListener);//注册监听
                mLocationService.start();//开始监听
                break;
        }
    }

    /*- 关闭当前activity,传值给storefragment -*/
    private void setResultToFragment() {
        Intent intent = new Intent(this, HomeActivity.class);
        Logger.d("provinceId:" + mProvinceAreaId + "++++++cityId:" + mCityAreaId);
        intent.putExtra("provinceId", mProvinceAreaId);
        intent.putExtra("cityId", mCityAreaId);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResultToFragment();
        super.onBackPressed();
    }

    /*- 重新显示省列表供选择 -*/
    private void showProvinces() {
        if (mRvProvinces.getVisibility() == View.GONE) {//省隐藏了
            mRvCities.setVisibility(View.GONE);
            mRvProvinces.setVisibility(View.VISIBLE);
            mTvActionBarTitle.setText("选择省份");
            mTvProvince.setText(mProvinceAreaName);
            mSelectorProvinceState = false;
            mClickProvincePosition = -1;
            mStvProvinceLabel.setVisibility(View.GONE);
            mTvSelectorProvince.setSelected(false);
        } else if (mRvProvinces.getVisibility() == View.VISIBLE && mSelectorProvinceState == true) {
            mSelectorProvinceState = false;
            mClickProvincePosition = -1;
            mStvProvinceLabel.setVisibility(View.GONE);
            mTvSelectorProvince.setSelected(false);
        }
    }

    /*- 自定义监听 -*/
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null && bdLocation.getLocType() != BDLocation.TypeServerError) {
                String city = bdLocation.getAddress().city;
                for (JSONObject oject : mCityList) {
                    if (oject.getString("area_name").equals(city)) {
                        mProvinceAreaId = oject.getString("area_parent_id");
                        mCityAreaId = oject.getString("area_id");
                    }
                }
                mTvProvince.setText(bdLocation.getAddress().province + city);
            } else {
                Toast.makeText(SelectorCityActivity.this, "定位失败,请重新定位!", Toast.LENGTH_SHORT).show();
            }
            mLocationLoadingDialog.dismiss();
            mLocationService.stop();
            mLocationService.unregisterListener(mMyLocationListener);
        }
    }
}